﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SignetKA.utils
{
    public class ColorTool
    {
        public static Bitmap ScaleToRect(Image image, Rectangle rect)
        {
            // 简单放大图片，这里将图片尺寸放大一倍（实际可能需要更合理的缩放算法）
            var scaleW = rect.Width * 1.0f / image.Width;
            var scaleH = rect.Height * 1.0f / image.Height;
            int newWidth = (int)((scaleW > scaleH ? scaleH : scaleW)* image.Width);
            int newHeight = (int)((scaleW > scaleH ? scaleH : scaleW) * image.Height);
            Bitmap enlargedBitmap = new Bitmap(newWidth, newHeight);
            using (Graphics g = Graphics.FromImage(enlargedBitmap))
            {
                g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
                g.DrawImage(image, 0, 0, newWidth, newHeight);
            }
            return enlargedBitmap;
        }
        public static Bitmap RemoveColor(Bitmap image, Color colorToRemove, int threshold = 50)
        {
            Color replacementColor = Color.Transparent; // 替换颜色

            // 调用高性能方法
            RemoveColorWithThreshold(image, colorToRemove, threshold, replacementColor);
            return image;
        }

        static void RemoveColorWithThreshold(Bitmap image, Color colorToRemove, int threshold, Color replacementColor)
        {
            // 锁定图像数据
            Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
            BitmapData bmpData = image.LockBits(rect, ImageLockMode.ReadWrite, image.PixelFormat);

            // 获取像素格式的字节数
            int bytesPerPixel = Image.GetPixelFormatSize(image.PixelFormat) / 8;
            int byteCount = bmpData.Stride * image.Height;
            byte[] pixelData = new byte[byteCount];

            // 复制图像数据到字节数组
            System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, pixelData, 0, byteCount);

            // 预计算阈值平方
            int maxAllowedDistanceSquared = threshold * threshold;

            // 遍历每个像素
            for (int y = 0; y < image.Height; y++)
            {
                for (int x = 0; x < image.Width; x++)
                {
                    // 计算当前像素的起始索引
                    int index = y * bmpData.Stride + x * bytesPerPixel;

                    // 获取当前像素的颜色分量
                    byte blue = pixelData[index];
                    byte green = pixelData[index + 1];
                    byte red = pixelData[index + 2];

                    // 计算颜色距离平方
                    int deltaR = red - colorToRemove.R;
                    int deltaG = green - colorToRemove.G;
                    int deltaB = blue - colorToRemove.B;
                    int distanceSquared = deltaR * deltaR + deltaG * deltaG + deltaB * deltaB;

                    // 如果颜色在阈值范围内，则替换为透明
                    if (distanceSquared <= maxAllowedDistanceSquared)
                    {
                        pixelData[index] = replacementColor.B;     // Blue
                        pixelData[index + 1] = replacementColor.G; // Green
                        pixelData[index + 2] = replacementColor.R; // Red
                        pixelData[index + 3] = replacementColor.A; // Alpha（透明度）
                    }
                }
            }

            // 将修改后的数据复制回图像
            System.Runtime.InteropServices.Marshal.Copy(pixelData, 0, bmpData.Scan0, byteCount);

            // 解锁图像数据
            image.UnlockBits(bmpData);
        }

        public static Bitmap RemoveColorByHSV(Bitmap image, Color colorToRemove, float hueThreshold = 0.1f, float saturationThreshold = 0.2f, float valueThreshold = 0.2f)
        {
            Color replacementColor = Color.Transparent; // 替换颜色

            // 调用基于 HSV 的颜色删除方法
            RemoveColorWithHSVThreshold(image, colorToRemove, hueThreshold, saturationThreshold, valueThreshold, replacementColor);
            return image;
        }
        static void RemoveColorWithHSVThreshold(Bitmap image, Color colorToRemove, float hueThreshold, float saturationThreshold, float valueThreshold, Color replacementColor)
        {
            // 将目标颜色转换为 HSV
            (float targetHue, float targetSaturation, float targetValue) = RgbToHsv(colorToRemove);

            // 锁定图像数据
            Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
            BitmapData bmpData = image.LockBits(rect, ImageLockMode.ReadWrite, image.PixelFormat);

            // 获取像素格式的字节数
            int bytesPerPixel = Image.GetPixelFormatSize(image.PixelFormat) / 8;
            int byteCount = bmpData.Stride * image.Height;
            byte[] pixelData = new byte[byteCount];

            // 复制图像数据到字节数组
            System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, pixelData, 0, byteCount);

            // 遍历每个像素
            for (int y = 0; y < image.Height; y++)
            {
                for (int x = 0; x < image.Width; x++)
                {
                    // 计算当前像素的起始索引
                    int index = y * bmpData.Stride + x * bytesPerPixel;

                    // 获取当前像素的颜色分量
                    byte blue = pixelData[index];
                    byte green = pixelData[index + 1];
                    byte red = pixelData[index + 2];

                    // 将 RGB 转换为 HSV
                    (float hue, float saturation, float value) = RgbToHsv(red, green, blue);

                    // 计算 HSV 分量的差值
                    float hueDifference = Math.Abs(hue - targetHue);
                    float saturationDifference = Math.Abs(saturation - targetSaturation);
                    float valueDifference = Math.Abs(value - targetValue);

                    // 如果颜色在阈值范围内，则替换为透明
                    if (hueDifference <= hueThreshold &&
                        saturationDifference <= saturationThreshold &&
                        valueDifference <= valueThreshold)
                    {
                        pixelData[index] = replacementColor.B;     // Blue
                        pixelData[index + 1] = replacementColor.G; // Green
                        pixelData[index + 2] = replacementColor.R; // Red
                        pixelData[index + 3] = replacementColor.A; // Alpha（透明度）
                    }
                }
            }

            // 将修改后的数据复制回图像
            System.Runtime.InteropServices.Marshal.Copy(pixelData, 0, bmpData.Scan0, byteCount);

            // 解锁图像数据
            image.UnlockBits(bmpData);
        }

        // 将 RGB 颜色转换为 HSV
        static (float Hue, float Saturation, float Value) RgbToHsv(int red, int green, int blue)
        {
            float r = red / 255f;
            float g = green / 255f;
            float b = blue / 255f;

            float max = Math.Max(r, Math.Max(g, b));
            float min = Math.Min(r, Math.Min(g, b));
            float delta = max - min;

            // 计算色相（Hue）
            float hue = 0;
            if (delta != 0)
            {
                if (max == r) hue = (g - b) / delta % 6;
                else if (max == g) hue = (b - r) / delta + 2;
                else if (max == b) hue = (r - g) / delta + 4;
                hue *= 60;
                if (hue < 0) hue += 360;
            }

            // 计算饱和度（Saturation）
            float saturation = max == 0 ? 0 : delta / max;

            // 计算明度（Value）
            float value = max;

            // 归一化到 [0, 1]
            return (hue / 360f, saturation, value);
        }

        // 重载方法：直接接受 Color 对象
        static (float Hue, float Saturation, float Value) RgbToHsv(Color color)
        {
            return RgbToHsv(color.R, color.G, color.B);
        }
    }
}
